<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart, BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { User, UserFilled, Calendar, FirstAidKit } from '@element-plus/icons-vue'
import gsap from 'gsap'
import dayjs from 'dayjs'
import { getApiUrl, API_ENDPOINTS } from '../config/api'

// Register ECharts components
echarts.use([
  CanvasRenderer,
  LineChart,
  PieChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

const statistics = ref({
  totalResidents: 0,
  totalStaff: 0,
  activeActivities: 0,
  medicalAlerts: 0
})

const loading = ref(false)

const healthStatusOption = ref({
  title: {
    text: '住户健康状态分布',
    left: 'center',
    top: 20,
    textStyle: {
      color: '#1d1d1f',
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    top: 'middle'
  },
  series: [
    {
      name: '健康状态',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
})

const activityTrendOption = ref({
  title: {
    text: '近期活动参与趋势',
    left: 'center',
    top: 20,
    textStyle: {
      color: '#1d1d1f',
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      color: '#1d1d1f'
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      color: '#1d1d1f'
    }
  },
  series: [
    {
      data: [],
      type: 'line',
      smooth: true,
      symbolSize: 8,
      lineStyle: {
        color: '#0071e3',
        width: 3
      },
      itemStyle: {
        color: '#0071e3'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(0,113,227,0.3)'
            },
            {
              offset: 1,
              color: 'rgba(0,113,227,0)'
            }
          ]
        }
      }
    }
  ]
})

const staffDistributionOption = ref({
  title: {
    text: '员工部门分布',
    left: 'center',
    top: 20,
    textStyle: {
      color: '#1d1d1f',
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['护理部', '医疗部', '后勤部', '活动部', '行政部'],
    axisLabel: {
      color: '#1d1d1f'
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      color: '#1d1d1f'
    }
  },
  series: [
    {
      data: [],
      type: 'bar',
      barWidth: '60%',
      itemStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: '#0071e3'
            },
            {
              offset: 1,
              color: '#40a9ff'
            }
          ]
        },
        borderRadius: [8, 8, 0, 0]
      }
    }
  ]
})

// Fetch dashboard data
const fetchDashboardData = async () => {
  try {
    loading.value = true
    
    // Use Promise.allSettled to handle partial failures
    const responses = await Promise.allSettled([
      fetch(getApiUrl(API_ENDPOINTS.residents)),
      fetch(getApiUrl(API_ENDPOINTS.staff)),
      fetch(getApiUrl(API_ENDPOINTS.activities)),
      fetch(getApiUrl(API_ENDPOINTS.medical))
    ])

    // Process responses
    const data = await Promise.all(
      responses.map(async (response) => {
        if (response.status === 'fulfilled' && response.value.ok) {
          return await response.value.json()
        }
        return []
      })
    )

    const [residentsData, staffData, activitiesData, medicalData] = data

    // Update statistics
    if (Array.isArray(residentsData)) {
      statistics.value.totalResidents = residentsData.length
      
      // Update health status chart
      const healthStatusCount = residentsData.reduce((acc, resident) => {
        acc[resident.healthStatus] = (acc[resident.healthStatus] || 0) + 1
        return acc
      }, {})

      healthStatusOption.value.series[0].data = Object.entries(healthStatusCount).map(([status, count]) => ({
        name: status,
        value: count
      }))
    }

    if (Array.isArray(staffData)) {
      statistics.value.totalStaff = staffData.length

      // Update staff distribution chart
      const departmentCount = staffData.reduce((acc, staff) => {
        acc[staff.department] = (acc[staff.department] || 0) + 1
        return acc
      }, {})

      staffDistributionOption.value.series[0].data = staffDistributionOption.value.xAxis.data.map(
        dept => departmentCount[dept] || 0
      )
    }

    if (Array.isArray(activitiesData)) {
      statistics.value.activeActivities = activitiesData.filter(
        activity => activity.status === '进行中'
      ).length

      // Update activity trend chart
      const last7Days = Array.from({ length: 7 }, (_, i) => {
        return dayjs().subtract(i, 'day').format('MM-DD')
      }).reverse()

      const activityCounts = last7Days.map(date => {
        return activitiesData.filter(
          activity => dayjs(activity.date).format('MM-DD') === date
        ).length
      })

      activityTrendOption.value.xAxis.data = last7Days
      activityTrendOption.value.series[0].data = activityCounts
    }

    if (Array.isArray(medicalData)) {
      statistics.value.medicalAlerts = medicalData.filter(
        record => record.status === '待处理'
      ).length
    }
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
  } finally {
    loading.value = false
  }
}

// Auto refresh data every minute
let refreshInterval: number

onMounted(() => {
  fetchDashboardData()
  
  // Add entrance animation
  const cards = document.querySelectorAll('.stat-card')
  gsap.from(cards, {
    duration: 0.8,
    y: 20,
    opacity: 0,
    stagger: 0.1,
    ease: 'power3.out'
  })

  // Set up auto refresh
  refreshInterval = window.setInterval(fetchDashboardData, 60 * 1000)
})

onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<template>
  <div class="dashboard">
    <h1 class="dashboard-title">欢迎回来</h1>
    <p class="dashboard-subtitle">今日概览</p>
    
    <el-row :gutter="24" class="stat-grid">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card" v-loading="loading">
          <div class="stat-content">
            <div class="stat-icon residents">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <span class="stat-label">入住人数</span>
              <span class="stat-value">{{ statistics.totalResidents }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card" v-loading="loading">
          <div class="stat-content">
            <div class="stat-icon staff">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <span class="stat-label">工作人员</span>
              <span class="stat-value">{{ statistics.totalStaff }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card" v-loading="loading">
          <div class="stat-content">
            <div class="stat-icon activities">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <span class="stat-label">进行中活动</span>
              <span class="stat-value">{{ statistics.activeActivities }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card" v-loading="loading">
          <div class="stat-content">
            <div class="stat-icon alerts">
              <el-icon><FirstAidKit /></el-icon>
            </div>
            <div class="stat-info">
              <span class="stat-label">医疗提醒</span>
              <span class="stat-value warning">{{ statistics.medicalAlerts }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="24" class="chart-row">
      <el-col :span="8">
        <el-card class="chart-card" v-loading="loading">
          <v-chart class="chart" :option="healthStatusOption" autoresize />
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="chart-card" v-loading="loading">
          <v-chart class="chart" :option="activityTrendOption" autoresize />
        </el-card>
      </el-col>
    </el-row>

    <el-row class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card" v-loading="loading">
          <v-chart class="chart" :option="staffDistributionOption" autoresize />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.dashboard-title {
  font-size: 32px;
  margin-bottom: 8px;
  background: linear-gradient(135deg, var(--primary-color), #40a9ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: bold;
}

.dashboard-subtitle {
  font-size: 16px;
  color: var(--text-secondary);
  margin-bottom: 32px;
}

.stat-grid {
  margin-top: 24px;
}

.stat-card {
  height: 140px;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  
  &.residents {
    background: rgba(24, 144, 255, 0.1);
    color: #1890ff;
  }
  
  &.staff {
    background: rgba(82, 196, 26, 0.1);
    color: #52c41a;
  }
  
  &.activities {
    background: rgba(250, 173, 20, 0.1);
    color: #faad14;
  }
  
  &.alerts {
    background: rgba(245, 34, 45, 0.1);
    color: #f5222d;
  }
}

.stat-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: var(--text-color);
  
  &.warning {
    color: #f5222d;
  }
}

.chart-row {
  margin-top: 24px;
}

.chart-card {
  padding: 20px;
  height: 400px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.chart {
  width: 100%;
  height: 360px;
}
</style>